package com.neusoft.javafxdemo2.controller;

import com.neusoft.javafxdemo2.common.AlertUtils;
import com.neusoft.javafxdemo2.common.FileUtils;
import com.neusoft.javafxdemo2.entity.Supervisor;
import javafx.fxml.FXML;
import javafx.scene.control.*;
import javafx.scene.text.Text;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.HashMap;
import java.util.Map;

public class SupervisorRegisterViewController {
    @FXML
    private TextField txtTelId;
    @FXML
    private PasswordField txtPassword, txtConfirmPassword;
    @FXML
    private TextField txtRealName;
    @FXML
    private RadioButton rdMale, rdFemale;
    @FXML
    private ToggleGroup genderGroup;//单选按钮选项组

    //界面初始化方法:方法名必须为：initialize(),在界面启动的时候系统自动调用这个方法，我们在这个方法中对组件进行一些初始化的操作。
    @FXML
    public void initialize() {
        //将性别按钮设置为一个选项组
        genderGroup = new ToggleGroup();
        rdMale.setToggleGroup(genderGroup);
        rdFemale.setToggleGroup(genderGroup);
    }

    public void saveSupervisor() {
        String telId = txtTelId.getText();
        String password = txtPassword.getText();
        String confirmPassword = txtConfirmPassword.getText();
        String realName = txtRealName.getText();
        //获取性别的值
        String gender = ((RadioButton) genderGroup.getSelectedToggle()).getText();
        //验证两次输入的密码是否一致:equals方法比较两个字符串是否相等
        if (!password.equals(confirmPassword)) {
            //弹出对话框，提示错误消息，结束注册流程
            AlertUtils.showDialog("用户注册","两次密码不一致");
            return;
        }
        System.out.println(telId + ":" + confirmPassword + ":" + password + ":" + realName + ":" + gender);
        Supervisor supervisor = new Supervisor(telId, password, realName, gender);
        //先将supervisor.txt文件中的map集合读取出来
        Map<String, Supervisor> map = FileUtils.readObject("supervisor.txt");
        //将新注册的supervisor对象放入从文件读取的map集合中
        map.put(supervisor.getTelId(), supervisor);
        //将map对象写入到supervisor.txt文件中
        FileUtils.writeObject("supervisor.txt",map);
        //弹出对话框，提示错误消息，结束注册流程
        AlertUtils.showDialog("用户注册","注册成功");
        //跳转到登录界面
        AlertUtils.switchToView(txtTelId,"SupervisorLoginView.fxml");
    }
    public void back(){
        //跳转到登录界面
        AlertUtils.switchToView(txtTelId,"SupervisorLoginView.fxml");
    }
}
